home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / ans / chap8 / exer0801 / Quad.java
Encoding:
Java Source  |  1997-04-20  |  835 b   |  29 lines

  1. class Quad {
  2.    public static void main(String[] args) {
  3.       Quad q = new Quad();
  4.       try {
  5.          double[] answer = q.roots(1.2, 3.2, -4.0);
  6.          System.out.println("The roots are " +
  7.             answer[0] + ", " + answer[1]);
  8.       } catch (NoRootsException x) {
  9.          System.out.println("No roots exist");
  10.       }
  11.    }
  12.  
  13.    double[] roots(double a, double b, double c) throws NoRootsException {
  14.       double[] result = new double[2];
  15.       double temp = (b * b) - ( 4 * a * c);
  16.       if (temp < 0)
  17.          throw new NoRootsException();
  18.       if (a < 0)
  19.          throw new NoRootsException();
  20.       temp = Math.sqrt(temp);
  21.       result[0] = (- b + temp) / (2.0 * a);
  22.       result[1] = (- b - temp) / (2.0 * a);
  23.       return result;
  24.    }
  25.       
  26. }
  27.  
  28. class NoRootsException extends Exception { }
  29.